<template>
  <a-spin :spinning="confirmLoading">
    <a-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="申请单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input disabled v-model="model.code" placeholder=""></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="审批流程" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="flowType">
              <j-dict-select-tag
                type="list"
                v-model="model.flowType"
                dictCode="material_application_flow_type"
                placeholder="请选择审批流程"
                :disabled="formDisabled"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="到货日期"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="arrivalDate"
            >
              <j-date
                placeholder="请选择日期"
                v-model="model.arrivalDate"
                style="width: 100%"
                :disabled="formDisabled"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item
              label="申请人"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="applyBy"
            >
              <a-input-search
                v-model="model.applyUserName"
                placeholder="请输入申请人"
                readonly
                enter-button
                @search="handleSelectUser1"
                :disabled="formDisabled"
              ></a-input-search>
              <a-input v-model="model.applyBy" hidden></a-input>
            </a-form-model-item>
          </a-col>
          <Tsl-Select-User-Single ref="selectUserModal1" @selectFinished="selectOK"></Tsl-Select-User-Single>
          <a-col :span="8">
            <a-form-model-item
              label="申请部门"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="sysOrgCode"
            >
              <!--部门可选：-->
              <!--<j-select-depart
                v-model="model.sysOrgCodeName"
                :trigger-change="true"
                customReturnField="id"
                :multi="false"
                :disabled="disabled"
              ></j-select-depart>-->
              <!--部门由申请人自动带出：-->
              <a-input v-model="model.sysOrgCodeName" placeholder="申请部门在选择申请人后自动带出" style="width: 100%" :disabled="true"></a-input>
              <a-input v-model="model.sysOrgCode" hidden></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="申请日期"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="tjdate"
            >
              <j-date
                placeholder="请选择日期"
                v-model="model.tjdate"
                style="width: 100%"
                :disabled="formDisabled"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">

          </a-col>
        </a-row>

        <a-row>
          <a-col :span="8">
            <a-form-model-item label="用途" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="useDesc">
              <a-input v-model="model.useDesc" placeholder="请输入用途" style="width: 400%" :disabled="formDisabled"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-input v-model="model.sourceFrom" type="hidden" />
      </a-form-model>
    </a-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="请购明细" :key="refKeys[0]" :forceRender="true">
        <a-row>
          <a-col :span="24">
            <!-- 表格 -->
            <j-vxe-table
              keep-source
              :ref="refKeys[0]"
              :loading="bussMaterialApplicationDetailTable.loading"
              :columns="bussMaterialApplicationDetailTable.columns"
              :dataSource="bussMaterialApplicationDetailTable.dataSource"
              :maxHeight="300"
              :disabled="formDisabled"
              :rowNumber="true"
              :rowSelection="false"
              :toolbar="true"
              :toolbarConfig="{ slot: ['prefix', 'suffix'], btn: ['clearSelection'] }"
              class="bold-border"
              :clickSelectRow="true"
              rowSelectionType="radio"
            >
              <template v-slot:toolbarSuffix>
                <a-button
                  type="primary"
                  icon="PlusCircleOutlined"
                  @click="addMateriel"
                  :disabled="formDisabled"
                >新增</a-button>
              </template>
              <template v-slot:action="props">
                <a-popconfirm
                  v-show="!formDisabled"
                  title="确定删除吗？"
                  @confirm="handleDelDetail(props)"
                >
                  <a>删除</a>
                </a-popconfirm>
              </template>
            </j-vxe-table>
          </a-col>
        </a-row>
      </a-tab-pane>
    </a-tabs>
    <erp-goods-list-model ref="selectGoodsList" category="3" @goodsOk="goodsOk" checkval="radio"></erp-goods-list-model>
  </a-spin>
</template>

<script>
import ErpGoodsListModel from '@comp/base/modal/ErpGoodsListModal'
import { getAction, httpAction, postAction, putAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import EditableCell from '@comp/table/EditableCell'
import EmployeeListModal from '@/components/tsl/modules/EmployeeListModal.vue'
import TslSelectUserSingle from '@/components/tsl/TslSelectUserSingle.vue'
import moment from 'dayjs'
import store from '@/store'
import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
import TslHistory from '@comp/tsl/TslHistory.vue'
import { definitionStartByDataId, isFirstInitiator } from '@views/flowable/api/definition'

export default {
  name: 'BussMaterialApplicationForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer,
    ErpGoodsListModel,
    EditableCell,
    TslSelectUserSingle,
    JSelectDepart,
    TslHistory,
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: {
        code: '',
        details: [],
        flowType: 1,
        sysOrgCodeName: '',
        sourceFrom: '2'
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        /*code: [{ required: true, message: '请输入编号!' }],
        tjdate: [{ required: true, message: '请输入日期!' }],
        applyBy: [{ required: true, message: '请选择申请人!' }],
        applyleaderBy: [{ required: true, message: '请选择申请主管!' }],
        purchaseleaderBy: [{ required: true, message: '请选择采购主管!' }],*/
      },
      refKeys: ['bussMaterialApplicationDetail'],
      tableKeys: ['bussMaterialApplicationDetail'],
      activeKey: 'bussMaterialApplicationDetail',
      // 材料请购单明细
      bussMaterialApplicationDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '物料编号',
            key: 'materialCode',
            type: JVXETypes.normal,
            width: '150px',
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}', // 显示的文本
              },
            ],
          },
          {
            title: '物料名称',
            key: 'materialName',
            type: JVXETypes.normal,
            width: '150px',
          },
          {
            title: '规格型号',
            key: 'spec',
            type: JVXETypes.normal,
            width: '150px',
          },
          {
            title: '单位',
            key: 'unit',
            type: JVXETypes.normal,
            width: '80px',
          },
          {
            title: '库存可用数量',
            key: 'availInvNum',
            type: JVXETypes.normal,
            width: '150px',
          },
          {
            title: '请购数量',
            key: 'applyNum',
            type: JVXETypes.inputNumber,
            width: '150px',
            validateRules: [
              {
                required: false,
                message: '请输入${title}',
              },
            ],
          },
          {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            minWidth: '100px',
            align: 'center',
            slotName: 'action',
          },
        ],
      },
      url: {
        add: '/procurement/add',
        edit: '/procurement/edit',
        queryById: '/procurement/queryById',
        bussMaterialApplicationDetail: {
          list: '/procurement/detail',
        },
      },
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    customFormData: {
      type: Object,
      default: () => {
        return {}
      },
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    this.model.sourceFrom = '2'

    this.model.tjdate = moment().format('YYYY-MM-DD')
    let user = store.getters.userInfo
    if (!this.model.createBy) {
      this.model.createBy = user.username
      this.model.createOrgcode = user.departIds
    }

    //如果是审批流进来的时候要将审批流的数据显示出来
    if (this.customFormData.id != null) {
      this.model = this.customFormData
      //刷新子表数据
      this.editAfter()
    }
  },
  methods: {
    onCellChange(record, dataIndex, value) {
      this.$set(record, dataIndex, value)
    },
    onDelete(record) {
      const dataSource = [...this.model.details]
      this.model.details = dataSource.filter((item) => item !== record)
    },
    goodsOk(data) {
      let detailaaa = {}
      detailaaa.materialName = data.name
      detailaaa.materialCode = data.code
      detailaaa.materialId = data.id
      detailaaa.spec = data.noneSpec
      detailaaa.unit = data.meUnit_dictText
      detailaaa.availInvNum = data.existInventory
      this.bussMaterialApplicationDetailTable.dataSource.push(detailaaa)
      //这里不能加记录 否则会出现表格中显示相同的两行的问题
      //this.model.details.push(detailaaa)
    },
    addMateriel() {
      this.$nextTick(() => {
        this.$refs.selectGoodsList.add()
      })
    },
    addBefore() {
      this.bussMaterialApplicationDetailTable.dataSource = []
      this.getSequenceNum()
    },
    getSequenceNum() {
      let url = '/sys/fillRule/executeRuleByCode/hardware_apply_code'
      putAction(url, {}).then((res) => {
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          this.model.code = res.result
        }
      })
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    edit(record) {
      if (typeof this.editBefore === 'function') this.editBefore(record)
      this.visible = true
      this.activeKey = this.refKeys[0]
      this.$refs.form.resetFields()

      this.model = Object.assign({}, record)
      //如果没有明细先要复制一个空数组
      if (record.details == null) {
        this.model.details = []
      }
      // this.$set(this.model, "code", record.applicationCode)
      // console.log("id:",record.applicationId)
      // this.$set(this.model, "id", record.applicationId)
      // this.$set(this.model, "code", record.applicationCode)
      if (typeof this.editAfter === 'function') this.editAfter(this.model)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {})
      // 加载子表数据
      // if(!this.model.details){
      //   // Object.assign(this.model, {details:[]});
      //   this.$set(this.model, "details", [])
      // }
      if (this.model.id) {
        let params = { id: this.model.id }
        // this.requestSubData(this.url.bussMaterialApplicationDetail.list, params, this.model,"details")
        this.requestSubTableData(
          this.url.bussMaterialApplicationDetail.list,
          params,
          this.bussMaterialApplicationDetailTable
        )
        //刷新明细的时候 还要将这个数据传输到要提交的表单中
        if (this.bussMaterialApplicationDetailTable) {
          this.model.details = this.bussMaterialApplicationDetailTable.dataSource
        }
      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch((e) => {
            if (e.error === VALIDATE_FAILED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        bussMaterialApplicationDetailList: allValues.tablesValue[0].tableData,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    submitForm() {
      const that = this
      this.$refs.bussMaterialApplicationDetail.validateTable().then((errMap) => {
        if (errMap) {
          this.$message.error('请检查表单明细内容')
          return
        } else {
          // 触发表单验证
          this.$refs.form.validate((valid) => {
            if (valid) {
              that.confirmLoading = true
              let httpurl = ''
              let method = ''
              if (!this.model.id) {
                httpurl += this.url.add
                method = 'post'
              } else {
                httpurl += this.url.edit
                method = 'put'
              }
              //240906增加提交时要以最后的明细为准
              if (this.bussMaterialApplicationDetailTable && this.bussMaterialApplicationDetailTable.dataSource) {
                this.model.details = this.bussMaterialApplicationDetailTable.dataSource
                this.model.details.forEach((element) => {
                  element.id = null
                })
              }

              if (!this.model.details || this.model.details.length <= 0) {
                this.$message.warning('没有选择任何物料不能保存')
                that.confirmLoading = false
                return
              }
              /*let flag = false
              let numFlag = false
              let indexString = ''
              let numIndexString = ''
              for (let index = 0; index < this.model.details.length; index++) {
                if (this.model.details[index].arrivalDate == null) {
                  that.confirmLoading = false
                  if (indexString == '') {
                    indexString += index + 1
                  } else {
                    indexString = indexString + ',' + (index + 1)
                  }
                  flag = true
                }
                if (this.model.details[index].num == null) {
                  that.confirmLoading = false
                  if (numIndexString == '') {
                    numIndexString += index + 1
                  } else {
                    numIndexString = numIndexString + ',' + (index + 1)
                  }
                  numFlag = true
                }
              }
              if (numFlag) {
                this.$message.warning('第' + numIndexString + '条物料没有数量')
                return
              }
              if (flag) {
                this.$message.warning('第' + indexString + '条物料没有填写到货日期')
                return
              }*/

              httpAction(httpurl, this.model, method)
                .then((res) => {
                  if (res.success) {
                    //241119修改提交时还要判断是否直接进入审批流
                    /*if (!this.model.id) {
                      this.model.dataId = res.message
                      that.applySubmit(this.model)
                    }*/
                    that.$message.success('保存成功')
                    that.$emit('ok')
                  } else {
                    that.$message.warning(res.message)
                  }
                })
                .finally(() => {
                  that.confirmLoading = false
                })
            }
          })
        }
      })
    },
    applySubmit(record) {
      if (record.dataId && record.dataId.length < 1) {
        this.$message.error('审批时必须传入参数dataId')
        return
      }

      //对于自定义业务，判断是否是驳回或退回的第一个发起人节点
      isFirstInitiator(record.dataId, record).then((res) => {
        if (res.success && res.result) {
          // 只有第一次能自动申请
          return
        } else {
          let params = Object.assign(
            {
              dataId: record.dataId,
            },
            record
          )
          definitionStartByDataId(record.dataId, 'hardwareApplicationService', params)
            .then((res) => {
              if (res.success) {
                this.$message.success(res.message)
              } else {
                this.$message.error(res.message)
              }
            })
            .finally()
        }
      })
    },
    handleSelectUser1() {
      this.$refs.selectUserModal1.visible = true
    },
    selectOK(data) {
      this.model.applyUserName = data.employeeName
      this.model.applyBy = data.employeeCode
      this.model.sysOrgCodeName = data.departCode_dictText
      this.model.sysOrgCode = data.departCode
    },
    handleSelectUser2() {
      this.$refs.selectUserModal2.visible = true
    },
    selectOK2(data) {
      this.model.applyleaderUserName = data.employeeName
      this.model.applyleaderBy = data.employeeCode
    },
    handleSelectUser3() {
      this.$refs.selectUserModal3.visible = true
    },
    selectOK3(data) {
      this.model.purchaseleaderUserName = data.employeeName
      this.model.purchaseleaderBy = data.employeeCode
    },
    //防止提交多次
    handleOk() {},
    handleDelDetail(props) {
      props.target.removeRows(props.row)
      if (this.bussMaterialApplicationDetailTable.dataSource.length > 0) {
        this.bussMaterialApplicationDetailTable.dataSource.splice(
          this.bussMaterialApplicationDetailTable.dataSource.findIndex((d) => d.id === props.row.id),
          1
        )
      }
    },
  },
}
</script>

<style scoped></style>
